﻿using Common;
using DAL.QDD;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnJiHuaWei.QDA
{
    public partial class frmItemBrand : Form
    {
        public frmItemBrand()
        {
            InitializeComponent();
        }
        ItemBrandServices objItemBrandServices = new ItemBrandServices();
        //查询
        private void button1_Click(object sender, EventArgs e)
        {
            if (dgvSelect.Rows.Count > 0)
            {
                MessageBox.Show("请先清空已选择表中的数据", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
           
            string id = comID.Text.Trim();
            int zt = Currency.GetCon_PickingID(id);
            if (zt == -1)
            {
                MessageBox.Show("识别码不存在", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (zt < 5)
            {
                MessageBox.Show("此识别码还未回齐套货位,不能进行签单", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (zt == 6)
            {
                MessageBox.Show("此识别码已签单,不能重复签单", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            int x = objItemBrandServices.GetCon_PickingID(id, out string countryid, out string con);//自制件是否要签单，0_不用签，1_要签
            //if (x == -1)
            //{
            //    MessageBox.Show("国家代码:" + countryid + " 不在国家资料表中,请维护进去", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //    return;
            //}
            dgvZZJ.Rows.Clear();
            dgvWGJ.Rows.Clear();
            labcon.Text = con;//合同号
            int sumqtyzzj = 0;//自制件总数量
            int qtyzzj = 0;//自制件未签总数量
            int sumqtywgj = 0;//外购件总数量
            int qtywgj = 0;//外购件未签总数量

            DataTable dtzzj = objItemBrandServices.GetPLTtem(id, 0);//自制件

            if (dtzzj != null)
            {
                int index = 0;
                string item = null;
                int qty = 0;
                for (int i = 0; i < dtzzj.Rows.Count; i++)
                {
                    index = dgvZZJ.Rows.Add();
                    item = dtzzj.Rows[i]["Item"].ToString();
                    qty = Convert.ToInt32(dtzzj.Rows[i]["Qty"].ToString());
                    dgvZZJ.Rows[index].Cells[0].Value = item;
                    dgvZZJ.Rows[index].Cells[1].Value = dtzzj.Rows[i]["Qty"].ToString();
                   
                    if (item.IndexOf("已退库")<0)
                    {
                        sumqtyzzj += qty;
                        qtyzzj += qty;
                    }
                }
            }
            DataTable dtwgj = objItemBrandServices.GetPLTtem(id, 1);//外购件
            if (dtwgj != null)
            {
                int index = 0;
                string item = null;
                int qty = 0;
                for (int i = 0; i < dtwgj.Rows.Count; i++)
                {
                    index = dgvWGJ.Rows.Add();
                    item = dtwgj.Rows[i]["Item"].ToString();
                    qty = Convert.ToInt32(dtwgj.Rows[i]["Qty"].ToString());
                    dgvWGJ.Rows[index].Cells[0].Value = item;
                    dgvWGJ.Rows[index].Cells[1].Value = dtwgj.Rows[i]["Qty"].ToString();
                    if (item.IndexOf("已退库") < 0)
                    {
                        sumqtywgj += qty;
                        qtywgj += qty;
                    }
                   
                }
            }
            labzzjsumQty.Text = sumqtyzzj.ToString();
            labzzjQty.Text = qtyzzj.ToString();
            labwgjsumqty.Text = sumqtywgj.ToString();
            labwgjqty.Text = qtywgj.ToString();
        }
        //查询编码的品牌型号产地等相关信息
        private void dgvWGJ_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvBrand.Rows.Clear();
            if (dgvWGJ.Rows.Count == 0)
            {
                return;
            }
            int dgvrow = 0;
            string item = null;
            dgvrow = dgvWGJ.CurrentRow.Index;
            item = dgvWGJ.Rows[dgvrow].Cells[0].Value.ToString();
            DataTable dt = new DataTable();
            dt = objItemBrandServices.GetItemBrand(item);
            if (dt == null)
            {
                MessageBox.Show("没有此编码的品牌型号等相关信息", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }
            else
            {
                int index = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    index = dgvBrand.Rows.Add();
                    dgvBrand.Rows[index].Cells[0].Value = dt.Rows[i][0].ToString();
                    dgvBrand.Rows[index].Cells[1].Value = dt.Rows[i][1].ToString();
                    dgvBrand.Rows[index].Cells[2].Value = dt.Rows[i][2].ToString();
                    dgvBrand.Rows[index].Cells[3].Value = dt.Rows[i][3].ToString();
                    dgvBrand.Rows[index].Cells[4].Value = dt.Rows[i][4].ToString();
                }
            }
        }

        private void dgvZZJ_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!checkBox1.Checked)
            {
                MessageBox.Show("自制件签单未勾选,不能对自制件签单", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            dgvBrand.Rows.Clear();
            if (dgvZZJ.Rows.Count == 0)
            {
                return;
            }
            int dgvrow = 0;
            string item = null;
            dgvrow = dgvZZJ.CurrentRow.Index;
            item = dgvZZJ.Rows[dgvrow].Cells[0].Value.ToString();
            DataTable dt = new DataTable();
            dt = objItemBrandServices.GetItemBrand(item);
            if (dt == null)
            {
                MessageBox.Show("没有此编码的品牌型号等相关信息", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                int index = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    index = dgvBrand.Rows.Add();
                    dgvBrand.Rows[index].Cells[0].Value = dt.Rows[i][0].ToString();
                    dgvBrand.Rows[index].Cells[1].Value = dt.Rows[i][1].ToString();
                    dgvBrand.Rows[index].Cells[2].Value = dt.Rows[i][2].ToString();
                    dgvBrand.Rows[index].Cells[3].Value = dt.Rows[i][3].ToString();
                    dgvBrand.Rows[index].Cells[4].Value = dt.Rows[i][4].ToString();
                }
            }
        }

        private void dgvBrand_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 3)
            {
                return;
            }
            if (dgvBrand.Rows.Count == 0)
            {
                return;
            }
            int dgvrow = 0;
            string item = null;
            int qty = 0;
            dgvrow = dgvBrand.CurrentRow.Index;
            item = dgvBrand.Rows[dgvrow].Cells[0].Value.ToString().Trim();
            qty = Convert.ToInt32(dgvBrand.Rows[dgvrow].Cells[4].Value.ToString().Trim());
            if (qty <= 0)
            {
                MessageBox.Show("请输入大于0的数量", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            int index = 0;
            if (Compare(item, qty, out int x))
            {
                index = dgvSelect.Rows.Add();
                dgvSelect.Rows[index].Cells[0].Value = comID.Text.Trim();
                dgvSelect.Rows[index].Cells[1].Value = labcon.Text;
                dgvSelect.Rows[index].Cells[2].Value = item;
                dgvSelect.Rows[index].Cells[3].Value = dgvBrand.Rows[dgvrow].Cells[1].Value;
                dgvSelect.Rows[index].Cells[4].Value = dgvBrand.Rows[dgvrow].Cells[2].Value;
                dgvSelect.Rows[index].Cells[5].Value = dgvBrand.Rows[dgvrow].Cells[3].Value;
                dgvSelect.Rows[index].Cells[6].Value = qty;
                if (x == 1)//自制件
                {
                    labzzjQty.Text = (Convert.ToInt32(labzzjQty.Text) - qty).ToString();
                }
                else if (x == 2)//外购件
                {
                    labwgjqty.Text = (Convert.ToInt32(labwgjqty.Text) - qty).ToString();
                }

            }
        }
        //判断数量有没有超数
        private bool Compare(string item, int num, out int x)
        {
            x = 0;
            int qty = 0;//需求数量
            int yqty = 0;//已签数量
            //自制件
            if (dgvZZJ.Rows.Count > 0)
            {
                for (int i = 0; i < dgvZZJ.Rows.Count; i++)
                {
                    if (dgvZZJ.Rows[i].Cells[0].Value.ToString().Trim() == item)
                    {
                        qty = Convert.ToInt32(dgvZZJ.Rows[i].Cells[1].Value);
                        yqty = Convert.ToInt32(dgvZZJ.Rows[i].Cells[2].Value);
                        if ((yqty + num) > qty)
                        {
                            MessageBox.Show("超数", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            return false;
                        }
                        else if ((yqty + num) < qty)
                        {
                            dgvZZJ.Rows[i].Cells[2].Value = yqty + num;

                        }
                        else
                        {
                            dgvZZJ.Rows[i].Cells[2].Value = yqty + num;
                            dgvZZJ.Rows[i].DefaultCellStyle.BackColor = Color.Green;

                        }
                        x = 1;
                        return true;
                    }
                }
            }
            //外购件
            if (dgvWGJ.Rows.Count > 0)
            {
                string s1 = null;
                for (int i = 0; i < dgvWGJ.Rows.Count; i++)
                {
                    if (dgvWGJ.Rows[i].Cells[0].Value.ToString().Trim() == item)
                    {
                        qty = Convert.ToInt32(dgvWGJ.Rows[i].Cells[1].Value);
                        yqty = Convert.ToInt32(dgvWGJ.Rows[i].Cells[2].Value);
                        if ((yqty + num) > qty)
                        {
                            MessageBox.Show("超数", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            return false;
                        }
                        else if ((yqty + num) < qty)
                        {
                            dgvWGJ.Rows[i].Cells[2].Value = yqty + num;

                        }
                        else
                        {
                            dgvWGJ.Rows[i].Cells[2].Value = yqty + num;
                            dgvWGJ.Rows[i].DefaultCellStyle.BackColor = Color.Green;

                        }
                        x = 2;
                        return true;
                    }
                }
            }
            return false;
        }

        private void frmItemBrand_Load(object sender, EventArgs e)
        {
            if (Program.CurrentUserManagement.IsAdmins != 1 && string.Compare(Program.CurrentUserManagement.Dept, "箱单组") != 0)
            {
                button1.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
            }
            dgvBrand.Columns[0].ReadOnly = true;
            dgvBrand.Columns[1].ReadOnly = true;
            dgvBrand.Columns[2].ReadOnly = true;
            dgvBrand.Columns[3].ReadOnly = true;
            dgvBrand.Columns[4].ReadOnly = false;
        }

        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvSelect.Rows.Count == 0)
            {
                return;
            }
            DialogResult dr = MessageBox.Show("请确认是否要删除所选择的行", "系统消息", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            if (dr == DialogResult.OK)
            {
                int dgvrow = dgvSelect.CurrentRow.Index;
                string sitem = dgvSelect.Rows[dgvrow].Cells[2].Value.ToString().Trim();
                int sqty = Convert.ToInt32(dgvSelect.Rows[dgvrow].Cells[6].Value.ToString().Trim());
                //自制件
                if (dgvZZJ.Rows.Count > 0)
                {
                    for (int i = 0; i < dgvZZJ.Rows.Count; i++)
                    {
                        if (dgvZZJ.Rows[i].Cells[0].Value.ToString() == sitem)
                        {
                            dgvZZJ.Rows[i].Cells[2].Value = Convert.ToInt32(dgvZZJ.Rows[i].Cells[2].Value) - sqty;
                            dgvZZJ.Rows[i].DefaultCellStyle.BackColor = Color.White;
                            dgvSelect.Rows.Remove(dgvSelect.Rows[dgvrow]);//删除行
                            dgvZZJ.CurrentCell = dgvZZJ.Rows[i].Cells[2];
                            labzzjQty.Text = (Convert.ToInt32(labzzjQty.Text) + sqty).ToString();
                            return;
                        }
                    }
                }
                //外购件
                if (dgvWGJ.Rows.Count > 0)
                {
                    for (int i = 0; i < dgvWGJ.Rows.Count; i++)
                    {
                        if (dgvWGJ.Rows[i].Cells[0].Value.ToString() == sitem)
                        {
                            dgvWGJ.Rows[i].Cells[2].Value = Convert.ToInt32(dgvWGJ.Rows[i].Cells[2].Value) - sqty;
                            dgvWGJ.Rows[i].DefaultCellStyle.BackColor = Color.White;
                            dgvSelect.Rows.Remove(dgvSelect.Rows[dgvrow]);//删除行
                            dgvWGJ.CurrentCell = dgvWGJ.Rows[i].Cells[2];
                            labwgjqty.Text = (Convert.ToInt32(labwgjqty.Text) + sqty).ToString();
                            return;
                        }
                    }
                }

            }

        }
     
        //提交数据库
        private void button3_Click(object sender, EventArgs e)
        {
            string id = comID.Text.Trim();//识别码
            string con = labcon.Text;//合同号
            if (id.Length==0 || con.Length==0)
            {
                MessageBox.Show("识别码或合同号不能为空", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            DateTime dti = DateTime.Now;
            string sql = null;
            int x = objItemBrandServices.PositionNum(con); //判断合同号还有多少份单没有签单
            int y = objItemBrandServices.ConIsPhoto(con);//如果这个合同要拍照，返回5，否则返回6
            List<string> sqlList = new List<string>();
            if (dgvSelect.Rows.Count == 0 && dgvWGJ.Rows.Count==0 && dgvZZJ.Rows.Count>0 && checkBox1.Checked==false)//对不需要签单的识别码提交数据库
            {
                DialogResult dr = MessageBox.Show("是否要对不需要签单的识别码提交数据库", "系统消息", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                if (dr == DialogResult.OK)
                {
                    sql = $"update Con_Picking set SignTime='{dti}',PackageQtyStatus=6 where Con_PickingID='{id}'";
                    sqlList.Add(sql);
                    if (x == 1)
                    {
                        DateTime qtTime = Convert.ToDateTime(Currency.GetConDateTime(con, 2));//齐套时间
                        int nighthouse = Tools.DifferDate(qtTime, dti, Program.holidays, 1);
                        int qdCycle = Tools.DifferDate(qtTime, dti, Program.holidays, 2);//签单周期=提交时间-齐套时间
                        sql = $"update Contract set QD_Time='{dti}',QDCycle={qdCycle},QD_Cycle={nighthouse},PackageQtyStatus={y},CurrentException=0 where ContractNO='{con}'";
                        sqlList.Add(sql);
                        sql = "UPDATE Change SET Step7=0";
                        sqlList.Add(sql);
                    }
                    try
                    {
                        if (Currency.SubmitPL(sqlList))
                        {
                            dgvZZJ.Rows.Clear();
                            button2_Click(null, null);
                            cmboxContractNo_SelectedIndexChanged(null, null);
                        }
                        else
                        {
                            MessageBox.Show("提交失败", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {

                        throw ex;
                    }
                }
            }
            else
            {
                if (Convert.ToInt32(labwgjqty.Text) > 0)
                {
                    if (dgvSelect.Rows.Count == 0)
                    {
                        MessageBox.Show("已选择编码的表中无数据,不能提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
               
                if (checkBox1.Checked)
                {
                    if (Convert.ToInt32(labzzjQty.Text) > 0)
                    {
                        MessageBox.Show("自制件签单已选中,还剩下 " + labzzjQty.Text + " PCS没有签单,不能提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (Convert.ToInt32(labwgjqty.Text) > 0)
                {
                    MessageBox.Show("外购件还剩下 " + labwgjqty.Text + " PCS没有签单,不能提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (objItemBrandServices.BoolSignData(id))
                {
                    MessageBox.Show("数据库中已有此识别码的签单数据,不能重复提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                int sumqty = 0;
                for (int i = 0; i < dgvSelect.Rows.Count; i++)
                {
                    sumqty += Convert.ToInt32(dgvSelect.Rows[i].Cells[6].Value.ToString());
                    sql = "insert into SignData(Con_PickingID,ContractNO,Item,Brand,Model,Origin,PCS) values('{0}','{1}','{2}','{3}','{4}','{5}',{6})";
                    sql = string.Format(sql, id, con, dgvSelect.Rows[i].Cells[2].Value.ToString(), dgvSelect.Rows[i].Cells[3].Value.ToString(), dgvSelect.Rows[i].Cells[4].Value.ToString(), dgvSelect.Rows[i].Cells[5].Value.ToString(), Convert.ToInt32(dgvSelect.Rows[i].Cells[6].Value.ToString()));
                    sqlList.Add(sql);
                }
                if (checkBox1.Checked)
                {
                    if (sumqty != (Convert.ToInt32(labzzjsumQty.Text) + Convert.ToInt32(labwgjsumqty.Text)))
                    {
                        MessageBox.Show("已签单总数量与需求总数量不符,不能提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
                else
                {
                    if (sumqty != Convert.ToInt32(labwgjsumqty.Text))
                    {
                        MessageBox.Show("已签单总数量与外购件需求总数量不符,不能提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
                sql = "update Con_Picking set SignTime='{0}',PackageQtyStatus=6 where Con_PickingID='{1}'";
                sql = string.Format(sql, dti, id);
                sqlList.Add(sql);
                if (x == 1)
                {
                    DateTime qtTime = Convert.ToDateTime(Currency.GetConDateTime(con, 2));//齐套时间
                    int nighthouse = Tools.DifferDate(qtTime, dti, Program.holidays, 1);
                    int qdCycle = Tools.DifferDate(qtTime, dti, Program.holidays, 2);//签单周期=齐套时间-提交时间
                    sql = $"update Contract set QD_Time='{dti}',QDCycle={qdCycle},QD_Cycle={nighthouse},PackageQtyStatus={y},CurrentException=0 where ContractNO='{con}'";
                    sqlList.Add(sql);
                }
                try
                {
                    sql = "UPDATE Change SET Step7=0";
                    sqlList.Add(sql);
                    if (Currency.SubmitPL(sqlList))
                    {
                        button2_Click(null, null);
                        cmboxContractNo_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        MessageBox.Show("提交失败", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
            //如果是最后一份单，把多品牌型号的编码单独汇总到表时
            if (x==1)
            {
                DataTable dt = objItemBrandServices.GetSignDataItem(con);
                if (dt==null)
                {
                    MessageBox.Show($"合同号：{con} 所有单已签完", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                try
                {
                    Tools.DataTableToSQLServer(dt, "Different");
                    MessageBox.Show("已提交", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageBox.Show($"合同号：{con} 所有单已签完", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                catch (Exception ex)
                {

                    MessageBox.Show("多品牌型号数据提交失败,请联系开发人员，错误原因："+ex, "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
           
        }

        //清空已选择的编码表中的数据
        private void button2_Click(object sender, EventArgs e)
        {
            if (dgvSelect.Rows.Count == 0)
            {
                return;
            }
            DialogResult dr = MessageBox.Show("请确认是否要清空已选择的编码表中的数据", "系统消息", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            if (dr == DialogResult.OK)
            {
                dgvZZJ.Rows.Clear();
                dgvWGJ.Rows.Clear();
                dgvBrand.Rows.Clear();
                dgvSelect.Rows.Clear();
                labzzjsumQty.Text = "0";
                labzzjQty.Text = "0";
                labwgjsumqty.Text = "0";
                labwgjqty.Text = "0";
                labcon.Text = string.Empty;
                comID.Text = string.Empty;
            }
        }

        private void btnrefresh_Click(object sender, EventArgs e)
        {
            this.btnrefresh.Enabled = false;
            ThreadPool.QueueUserWorkItem(s => { Tools.Stopbtn(this, this.btnrefresh); });
            List<string> list = objItemBrandServices.GetQdcon();
            cmboxContractNo.DataSource = list;
        }

        private void cmboxContractNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string con = cmboxContractNo.Text.Trim();
            if (con.Length == 0)
            {
                return;
            }
            List<string> list = objItemBrandServices.GetQdid(con);
            comID.DataSource = list;
        }
    }
}



